﻿Imports System.Text
Imports System.Web
Imports System.Net
Imports System.IO
Imports Newtonsoft.Json
Imports Newtonsoft.Json.Linq


Public Class Twitter
    Const consumerKey = "votiop5aKIZemOvoRKy66w"
    Const consumerSecret = "YsNEQv1qF9Q5JCvVNS4VGRXOVDtvBRYLgaJFbTOjdE"
    Const accessToken = "38944502-rWM7UqzWeBGmJqo14KTj6DCsFnd1YmHcCTHWfdaoW"
    Const accessTokenSecret = "ESKEniOfVbJgzGlbGS90ujXaMi6bDVf5dZkzn7WDpY"
    Const authRequestURI = "https://api.twitter.com/oauth2/token"
    Const searchRequestURI = "https://api.twitter.com/1.1/search/tweets.json"

    Private Shared m_logger As LogWriter
    Private Shared m_accessToken As String
    Public m_imageList = New List(Of String)
    Private Shared m_LatestTweetID As Decimal = 0

    Public Sub New()
        'twitter class constructor
        'as soon as the class is loaded create an instance of the log writter and hold it within the twitter class for writing to
        Dim logger As LogWriter = New LogWriter()
        m_logger = logger

    End Sub

    Public Function search(KeyWord As String) As List(Of String)
        Dim searchString = "q=" & KeyWord
        Dim responseContent As String
        Dim matchedResponse As String = ""
        Dim twitterSearchRequest As HttpWebRequest = WebRequest.Create(searchRequestURI & "?" & searchString)
        twitterSearchRequest.Method = "GET"
        'attach our bearer access token to the header
        twitterSearchRequest.Headers.Add("Authorization: Bearer " & m_accessToken)
        twitterSearchRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8"

        Using twitterResponse As WebResponse = twitterSearchRequest.GetResponse()
            m_logger.writeToFormWindow("Sending search request")
            Using reader = New StreamReader(twitterResponse.GetResponseStream())

                responseContent = reader.ReadToEnd()
                m_logger.writeToFormWindow("Reading response")
            End Using
        End Using

        Dim jsonDat As Object = JObject.Parse(responseContent)
        'write to total tweets text box
        m_logger.writeTotalTweets(jsonDat("statuses").Count())
        For x As Integer = 0 To jsonDat("statuses").Count() - 1
            Dim tweet As JObject = JObject.Parse(jsonDat("statuses")(x).ToString())
            Try
                logLatestTweet(tweet("id"))
                Dim tweetLink As JObject = JObject.Parse(tweet("entities").ToString)
                m_logger.writeTotalImages(tweetLink("media").Count())
                For y As Integer = 0 To tweetLink("media").Count() - 1
                    m_imageList.Add(tweetLink("media")(0)("media_url").ToString)
                Next
            Catch ex As Exception
                'no image here
            End Try


        Next

        Return m_imageList

    End Function

    Private Shared Sub logLatestTweet(ByVal tweetID As Decimal)
        If tweetID > m_LatestTweetID Then
            m_LatestTweetID = tweetID
            m_logger.writeLatestTweetID(tweetID)
        End If

    End Sub

    Private Shared Function createoAuthHeader() As String
        'create the encoded authorization header based on twitter REST 1.1 API
        'https://dev.twitter.com/docs/auth/application-only-auth

        Dim bearerTokenCredentials As String

        'url encode the consumer key add a colon and url encode the consumer secret.  Base64 encode the whole thing
        bearerTokenCredentials = Convert.ToBase64String(New ASCIIEncoding().GetBytes(HttpUtility.UrlEncode(consumerKey) & ":" & HttpUtility.UrlEncode(consumerSecret)))
        'report the activity to our main form system log
        m_logger.writeToFormWindow("Created bearer token credentials")
        Return bearerTokenCredentials

    End Function

    Private Shared Function createRequest() As HttpWebRequest

        m_logger.writeToFormWindow("Creating credential request")

        'create the request based on the twitter REST 1.1 API
        'https://dev.twitter.com/docs/auth/application-only-auth

        Dim twitterAuthRequest As HttpWebRequest = WebRequest.Create(authRequestURI)
        'requesting the client credentials from the twitter api
        'this string will be written to the header body via request stream
        Dim requestBody = "grant_type=client_credentials"

        'must be a post over https to get the bearer access key
        twitterAuthRequest.Method = "POST"

        'attach our base64 encoded consumerkey and consumer secret to the header of our request
        twitterAuthRequest.Headers.Add("Authorization: Basic " & Twitter.createoAuthHeader())
        twitterAuthRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8"


        Using stream As Stream = twitterAuthRequest.GetRequestStream()
            Dim content(requestBody.Length) As Byte
            content = ASCIIEncoding.ASCII.GetBytes(requestBody)
            stream.Write(content, 0, content.Length)
        End Using

        m_logger.writeToFormWindow("Request created")

        Return twitterAuthRequest

    End Function

    Public Function getRequestResponse() As Boolean

        Dim twitterAuthRequest = Twitter.createRequest()

        Dim responseContent As String
        Using twitterResponse As WebResponse = twitterAuthRequest.GetResponse()
            m_logger.writeToFormWindow("Sending credential request")
            Using reader = New StreamReader(twitterResponse.GetResponseStream())

                responseContent = reader.ReadToEnd()
                m_logger.writeToFormWindow("Reading response")
            End Using
        End Using

        m_logger.writeToFormWindow("Response reseieved")


        If validateCredentials(responseContent) Then
            Return True
        Else
            Return False
        End If
    End Function

    Private Shared Function validateCredentials(responseContent As String) As Boolean
        Dim reader As JsonTextReader = New JsonTextReader(New StringReader(responseContent))
        Dim gotToken As Boolean = False
        Dim tempAccessToken As String = ""


        While (reader.Read())
            If (reader.Value <> Nothing And reader.TokenType = 9) Then
                m_logger.writeToFormWindow("Validating credentials")

                If reader.Path = "token_type" Then
                    If reader.Value = "bearer" Then
                        gotToken = True
                    End If
                End If
                If reader.Path = "access_token" Then
                    tempAccessToken = reader.Value
                End If

            End If
        End While

        If gotToken = True Then
            m_accessToken = tempAccessToken
            Return True
        Else
            Return False
        End If
    End Function

End Class

